package cn.wolfcode.shop.cloud.service.impl;
import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;
import cn.wolfcode.shop.cloud.msg.MemberCodeMsg;
import cn.wolfcode.shop.cloud.service.IUserService;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.Md5Util;
import cn.wolfcode.shop.cloud.util.MemberKeyPrefix;
import cn.wolfcode.shop.cloud.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public User get(Long id) {
        return userMapper.find(id);
    }

    @Override
    public Boolean refreshToken(String token) {
        //redis里存在就刷新,返回true
        boolean flg = redisService.exists(MemberKeyPrefix.USER_TOKEN, token);
        if (flg){
            redisService.expire(MemberKeyPrefix.USER_TOKEN, token);
            return true;
        }

        return null;
    }

    @Override
    public User getCurrent(String userToken) {
        if (StringUtils.isEmpty(userToken)){
            return null;
        }
        User user = redisService.get(MemberKeyPrefix.USER_TOKEN, userToken, User.class);

        return user;
    }

    @Override
    public String doLogin(LoginVO loginVO) {
        //做登录校验
        //如果用户名或密码为空
        if (StringUtils.isEmpty(loginVO.getUsername()) || StringUtils.isEmpty(loginVO.getPassword())) {
            throw new BusinessException(MemberCodeMsg.USERNAME_PASSWORD_NULL);
        }
        //string类型转换成long类型
        long id = Long.parseLong(loginVO.getUsername());
        User user = this.get(id);
        //判断用户是否存在
        if (user == null) {
            throw new BusinessException(MemberCodeMsg.USER_NOT_EXIST);
        }
        //把用户传入的密码，加密
        String encodePassword = Md5Util.encode(loginVO.getPassword(), user.getSalt());
         //判断密码是否正确,不正确抛异常
        if (!user.getPassword().equals(encodePassword)) {
            throw new BusinessException(MemberCodeMsg.USER_PASSWORD_ERROR);
        }
        //把用户信息存到redis中
        String token = createToken(user);
        return token;
    }

    private String createToken(User user) {
        // 把用户信息存到redis中; 前缀+token=relkey
        //生成token
        String token= UUID.randomUUID().toString().replaceAll("-","");
        redisService.set(MemberKeyPrefix.USER_TOKEN,token,user);
        return token;
    }
}
